<?php

namespace App\Repository\UpThree;

use App\Api\Logistics\TransferLogistics;
use App\Jobs\GetOrderStatus;
use App\Repository\Admin\AdminUsersLogRepository;
use App\Repository\BaseRepository;
use App\Repository\Order\OrderChannelRepository;
use App\Repository\Order\OrderProductRepository;
use App\Repository\Orders\OrdersLogisticsRepository;
use App\Repository\Orders\OrdersRepository;
use App\Repository\Product\GoodsRepository;
use App\Repository\Product\ProductRepository;
use App\Repository\Sms\SmsConfExpressRepository;
use App\Repository\Zhuandan\SmsZRepository;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;


class MainOrderTwoRepostition extends BaseRepository
{
    private $goodsModel = null;
    private $productModel = null;
    private $orderProductModel = null;
    private $channelModel = null;
    private $orderModel = null;
    private $userMoneyLog = null;
    private $log = null;
    private $logOrder = null;
    private $orderKeys = null;
    private $orderKeysTime = null;
    private $smsZModle = null;
    private $orderLogModle = null;

    public function __construct()
    {
        $this->goodsModel = new GoodsRepository();
        $this->productModel = new ProductRepository();
        $this->orderProductModel = new OrderProductRepository();
        $this->channelModel = new OrderChannelRepository();
        $this->orderModel = new OrdersRepository();
        $this->userMoneyLog = new AdminUsersLogRepository();
        $this->smsZModle = new SmsZRepository();
        $this->orderLogModle = new OrdersLogisticsRepository();
        $this->log = new Logger('ChinnelLogTwo');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChinnelLogTwo.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        // 记录的是 第三方成功了 但是本地失败了
        $this->logOrder = new Logger('ChinnelLogTwoOrders');
        $this->logOrder->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChinnelLogTwoOrders.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
        $this->orderKeys = '';
        $this->orderKeysTime = 5; //缓存多长时间
    }

    // 1: 设置短信发送
    // 2: 发送设置
    // 3: 物流详情记录  √
    //     3.1 应该设置在 物流回传的地方  √
    // 4: 物流追踪设置 mainorder的信息回传上面

    // 物流设置
    public function expressTrack($expressName, $expressNum)
    {
        if (empty($expressName) || empty($expressNum)) {
            return $this->returnMsg(101, '物流名称和物流单号不能为空');
        }
        // 只发送一次 判断是否重发
        $isTrue = $this->orderLogModle->getOne(['express_num' => $expressNum]);
        if ($isTrue) {
            return $this->returnMsg(109, '该物流已传递');
        }
        $model = new TransferLogistics();
        $data = [
            'name' => 'K100',
            'express_company' => $expressName,
            'express_number' => $expressNum,
        ];
        $res = $model->supscr($data);
        $addRes = [];
        if (!empty($res['code']) && $res['code'] == 200) {
            $datas = [
                'express_name' => $expressName,
                'express_num' => $expressNum,
            ];
            $addRes = $this->orderLogModle->add($datas);
        }
        $this->log->info('物流发送参数' . json_encode($data) . '返回结果:' . json_encode($res) . '数据插入返回:' . json_encode($addRes));
        return $res;
    }

    /**
     * 根据物流订单状态 发送短信
     */
    public function expressStatusSendSms($where = [], $isTrue = true)
    {
        $data = $this->orderModel->getOne($where);
        if (!$data) {
            return $this->returnMsg(100, '未查询到订单');
        }
        // var_dump($data);
        // 根据 goods_code 查询模板
        // 店铺 信息 添加一个 所有
        $whereSmsTmp = [
            // 'dist_id' => $data['shop_id'], // 去掉shop_id查询
            // 'goods_id' => $data['goods_id'],  // 去掉goods_id 的查询条件
            'product_code' => $data['product_code'], //  添加 goods_code的查询提交
            'express_status' => $data['express_status'],
            'status' => 0
        ];
        // var_dump($whereSmsTmp, 4444444444);
        $smsConfModel = new SmsConfExpressRepository();
        // var_dump($whereSmsTmp);
        $resConfDatas = $smsConfModel->getAll($whereSmsTmp);
        // var_dump($resConfDatas, 4444444);
        // die();
        if (empty($resConfDatas)) {
            return $this->returnMsg(200, '未查询到配置模板');
        }
        //查询主店铺是否要发送  自己店铺里面不配置短信 查询最上面的店铺查询是否发送短信
        $resConfData = [];
        if (!empty($resConfDatas)) {
            foreach ($resConfDatas as $key => $v) {

                if (!empty($data['shop_id_str'])) {
                    $resConfArr = explode('.', $data['shop_id_str']);
                    if ($v->dist_id == $v->shop_id && in_array($v->dist_id, $resConfArr)) {
                        // 代理配置的所有分销商和自己都会发送 自己店铺
                        $resConfData = $v;
                        break;
                    } else if (in_array($v->dist_id, $resConfArr)) {
                        $resConfData = $v;
                        break;
                    }
                }
                if (empty($data['shop_id_str'])) {
                    if ($v->dist_id == $v->shop_id && $v->dist_id == $data['shop_id']) {
                        // 代理配置的所有分销商和自己都会发送 自己店铺
                        $resConfData = $v;
                        break;
                    }
                }
            }
        }
        if (empty($resConfData)) {
            return $this->returnMsg(200, '未查询到配置模板');
        }
        $resConfData = json_decode(json_encode($resConfData), true);
        if (!empty($resConfData['delay'])) {
            $time = $resConfData['delay'] * 60 * 60;
            // var_dump($times);
            $resDataDelay = [
                'data' => $data,
                'confData' => $resConfData
            ];
            // dispatch(new OrderSubmit($resDataDelay, 'sendSms', $time))->onQueue('TaskOrderSubmitDispose');
            dispatch(new GetOrderStatus($resDataDelay, 'sendExpressSms', 10))->onQueue('TaskGetOrderStatusDispose'); // 定时更新状态
            return $this->returnMsg(200, '延迟发送');
        }
        // 判断是否发送过已经发送过信息
        return $this->isSmsAndSend($data, $resConfData, false);
    }

    /**
     * 判断是否发过短信 + 发送短信
     *
     * @param array $data 订单数据
     * @param array $smsTmp 短信模板数据
     * @return array
     */
    public function isSmsAndSend($data = [], $smsTmp = [], $isZ = false)
    {
        $Repostion = new MainOrderRepostition();
        return $Repostion->isSmsAndSend($data, $smsTmp, $isZ);
//        // var_dump($smsTmp);
//        if (empty($smsTmp['express_status']) || empty($data['express_status'])) {
//            return $this->returnMsg(103, '订单状态为空');
//        }
//        if (!empty($smsTmp['express_status']) && !empty($data['express_status'])) {
//            $orderArr = explode(',', $smsTmp['express_status']);
//            if (!in_array($data['express_status'], $orderArr)) {
//                return $this->returnMsg(103, '订单状态已更新不用发送');
//            }
//        }
//        // 判断是否发送过已经发送过信息
//        $whereLog = [
//            'sms_tmp_id' => $smsTmp['sms_tmp_id'],
//            'express_status' => $data['express_status'],
//            'order_id' => $data['id'],
//            'is_send' => 2,
//        ];
//        $isCharge = true;
//        $logModel = new SmsSendLogRepository();
//        $resLog = $logModel->getOne($whereLog);
//        if ($resLog && $resLog->status == 0) {
//            return $this->returnMsg(200, '已发送');
//        }
//        if (isset($resLog->status) && $resLog->status != 0) {
//            $isCharge = false;
//        }
//        $whereTmp = [
//            'id' => $smsTmp['sms_tmp_id'],
//        ];
//        $tmpModel = new SmsTmpRepository();
//        $tmpData = $tmpModel->getOne($whereTmp);
//        if (empty($tmpData)) {
//            return $this->returnMsg(2, '未查询到模板');
//        }
//        if (!empty($tmpData)) {
//            $tmpData = json_decode(json_encode($tmpData), true);
//        }
//        $tmpData['phone'] = (empty($smsTmp['is_phone']) || ($smsTmp['is_phone'] == 1)) ? $data['pay_phone'] : $data['iccid'];
//        // 短信内容替换
//        $tmpData['content'] = str_replace('(快递)', $data['express_company'], $tmpData['content']);
//        $tmpData['content'] = str_replace('(快递单号)', $data['express_number'], $tmpData['content']);
//        $smsTmp['is_send'] = 2;
//        $smsTmp['status'] = 1;
//        $smsTmp['phone'] = $tmpData['phone'];
//        $smsTmp['content'] = $tmpData['content'];
//        $smsTmp['order_id'] = $data['id'];
//        $smsTmp['express_status'] = $data['express_status'];
//        // var_dump($smsTmp, 111111111);
//        if ($isZ) {
//            $smsTmp['remark'] = '原始套餐:' . $data['one_product_name'] . '上游套餐:' . $data['sup_product_name'];
//        }
//
//        $flag = true;
//        if ($isCharge) {
//            // 短信费用
//            // $resDe = $this->deductExpen($data, $data['shop_id'], 3);
//            // $smsTmp['reason'] = !empty($resDe['msg']) ? $resDe['msg'] : '';
//            // if (empty($resDe['code']) || $resDe['code'] != 200) {
//            //     $flag = false;
//            // }
//        }
//        // 默认发送失败
//        $resLogAdd = $logModel->add($smsTmp);
//        if (empty($resLogAdd['code']) || $resLogAdd['code'] != 200) {
//            return $resLogAdd;
//        }
//        if (empty($resLogAdd['data']['id'])) {
//            return $this->returnMsg(100, '短信记录插入失败');
//        }
//        $whereEdit = ['id' => $resLogAdd['data']['id']];
//        $editData = [];
//        if ($flag) {
//            $isSendMsg = true;
//            if (!empty($data['sell_name'])) {
//                $isAgren = DB::table('sms_agent')->where(['name' => $data['sell_name']])->first();
//                if (!empty($isAgren)) {
//                    $res = [
//                        'msg' => '该订单存在于分销商黑名单中'
//                    ];
//                    $isSendMsg = false;
//                }
//            }
//            // 短信发送是否开启
//            $resIsSms = DB::table('system')->where(['name' => 'is_sms'])->first();
//            if (!empty($resIsSms) && !empty($resIsSms->val) && $isSendMsg) {
//                $res = $this->pushSmsCline($tmpData);
//                $this->log->info('短信发送参数' . json_encode($tmpData) . '返回结果:' . json_encode($res));
//            }
//            if (!empty($res['code']) && $res['code'] == 200) {
//                // 扣费
//                $editData['status'] = 0;
//            }
//
//            $editData['reason'] = !empty($res['msg']) ? $res['msg'] : '';
//        }
//        // 修改发送状态
//        if (!empty($editData)) {
//            $resReslog = $logModel->edit($whereEdit, $editData);
//        }
//        return !empty($resReslog) ? $resReslog : $resLogAdd;
    }

    //发送短信方法
    public function pushSmsCline($data)
    {
//        $model = new TransferSms();
//        $res = $model->sendSms($data);
//        return $res;
    }
}
